/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.base.stack
 * author:David
 * Date:2015年6月13日下午5:46:05
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.base.stack;

/**
 * 栈的顺序存储实现
 * 
 * @author David
 * @since 2015年6月13日 下午5:46:05
 * @version
 * @since JDK 1.6
 */
public class StackArray implements Stack{
	private final int LEN = 8;// 数组的默认大小
	private Object[] elements;// 数组
	private Integer top;// 栈顶指针
	
	public StackArray(){
		top=-1;
		elements=new Integer[LEN];
	}

	@Override
	public int getSize() {
		// TODO Auto-generated method stub
		return top+1;
	}

	@Override
	public boolean isEmpty() {
		// TODO Auto-generated method stub
		return top<0;
	}

	@Override
	public void push(Object e) {
		// TODO Auto-generated method stub
		if(getSize()>=elements.length){
			expandSpace();
		}
		elements[++top]=e;
		
	}

	/**
	 * 扩大数组空间
	 */
	private void expandSpace() {
		Integer[]a=new Integer[elements.length*2];
		for(int i=0;i<elements.length;i++){
			a[i]=(Integer) elements[i];
		}
		elements=a;
	}

	@Override
	public Object pop() throws StackEmptyException {
		if(getSize()<1){
			throw new StackEmptyException("错误，栈为空！");
		}
		Integer obj=(Integer) elements[top];
		elements[top--]=null;
		return obj;
	}

	@Override
	public Object peek() throws StackEmptyException {
		if(getSize()<1){
			throw new StackEmptyException("错误，栈为空！");
		}
		return elements[top];
	}

}
